package com.example.java.table;

import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;

import static org.apache.flink.table.api.Expressions.$;

public class TableAPIMain {
    public static void main(String[] args) throws Exception {
        //Flink执行环境env
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //用env，做出Table环境tEnv
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        //获取流式数据源
        DataStreamSource<Tuple2<String, Long>> data = env.addSource(
                new SourceFunction<Tuple2<String, Long>>() {
                    private Long count = 0L;

                    @Override
                    public void run(SourceContext<Tuple2<String, Long>> ctx) throws Exception {
                        while (true) {
                            ctx.collect(new Tuple2<>("count", ++count));
                            Thread.sleep(1000);
                        }
                    }

                    @Override
                    public void cancel() {

                    }
                });
        //将流式数据源做成Table
        Table table = tEnv.fromDataStream(data, $("count"), $("num"));
        //对Table中的数据做查询
        Table name = table.select($("num"), $("count"));
        //将处理结果输出到控制台
        DataStream<Tuple2<Boolean, Row>> result = tEnv.toRetractStream(name, Row.class);
        result.print();
        env.execute();
    }
}
